<template>
  <div class="goTop"
    :style="background"
    v-show="goTopShow"
    @click="goTop">
    Top
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'GoTop',
  props: {
    height: Number
  },
  data () {
    return {
      scrollTop: '',
      goTopShow: false,
      background: {
        'background': ''
      }
    }
  },
  methods: {
    handleScroll () {
      this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      if (this.scrollTop > this.height) {
        this.goTopShow = true
      } else {
        this.goTopShow = false
      }
    },
    goTop () {
      let timer = null
      cancelAnimationFrame(timer)
      timer = requestAnimationFrame(function () {
        // if (_that.scrollTop > 0) {
        //   _that.scrollTop -= 50
        //   document.body.scrollTop = document.documentElement.scrollTop = _that.scrollTo
        //   timer = requestAnimationFrame()
        // } else {
        //   cancelAnimationFrame(timer)
        //   _that.goTopShow = false
        // }
        window.scrollTo({ top: 0, behavior: 'smooth' })
      })
    }
  },
  computed: {
    ...mapGetters([
      'getBackground'
    ])
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll)
    const color = this.getBackground
    this.background.background = color
  },
  destroyed () {
    window.removeEventListener('scroll', this.handleScroll)
  }
}
</script>

<style scoped lang="stylus">
  .goTop
    display flex
    justify-content center
    align-content center
    width: 50px;
    height: 50px;
    line-height: 50px;
    font-size: 16px;
    color: #ffffff;
    border-radius: 5px;
    cursor pointer
    opacity 0.7
  .goTop:hover
    opacity 1
</style>
